import { useRequest, useUpdateEffect } from 'ahooks'
import dayjs from 'dayjs'
import classnames from 'classnames'
import { Card, Collapse, Tag, Timeline } from 'antd'

import { VCenterEmpty } from '@/components/VCenterEmpty'
import { useControllerRef } from '@/hooks/useAbortController'
import { emptyDesc } from '../../utils'
import { withDelayRequest } from '../utils'
import { apiGetWaybillNumberRouteInfo } from './apis'
import styles from './styles.module.less'

const getWaybillNumberRouteInfo = withDelayRequest(apiGetWaybillNumberRouteInfo)

export const TransferOrderNumRoute = ({ waybillNo }: { waybillNo: string }) => {
  const controllerRef = useControllerRef()
  const { loading, data, mutate, run } = useRequest(() => {
    mutate(undefined)
    controllerRef.current.abort()
    controllerRef.current = new AbortController()
    return getWaybillNumberRouteInfo(waybillNo, controllerRef.current.signal)
  })

  useUpdateEffect(() => run(), [waybillNo])

  return (
    <Card style={{ minHeight: 410 }} className={styles.card} loading={loading}>
      {!data?.length ? (
        VCenterEmpty.render({ description: emptyDesc, style: { minHeight: 410 * 0.7 } })
      ) : (
        <Collapse
          accordion
          expandIconPosition="end"
          defaultActiveKey={data[0].trackingNumber}
          items={data.map(item => {
            return {
              key: item.trackingNumber,
              label: (
                <div className={styles.collapse_left}>
                  {item.logisticsCompany}:{item.trackingNumber}
                </div>
              ),
              children: (
                <Timeline
                  mode="left"
                  items={item.routeInfoList.map((child, index) => {
                    return {
                      label: (
                        <div className={styles.textTime}>
                          {child.eventTimeIso ? dayjs(child.eventTimeIso).$formatSmart($F_YMDHms) : ''}
                        </div>
                      ),
                      children: (
                        <div className={styles.routeContain}>
                          <div className={classnames(styles.textNew, index > 0 ? styles.textFilter : '')}>
                            {child.eventDetail}
                          </div>
                        </div>
                      ),
                      color: index === 0 ? 'blue' : 'gray',
                    }
                  })}
                />
              ),
              extra: <Tag>{item.latestStatus}</Tag>,
            }
          })}
        />
      )}
    </Card>
  )
}
